<template>
  <div class="app-container">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px">
      <el-form-item label="新闻类型" prop="newsType">
        <el-select v-model="ruleForm.newsType" clearable>
          <el-option
            v-for="item in newsTypeData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="新闻标题" prop="newsTitle">
        <el-input v-model="ruleForm.newsTitle"  maxlength="30"  clearable />
      </el-form-item>
      <el-form-item label="新闻描述" prop="titleContent">
        <el-input v-model="ruleForm.titleContent" clearable />
      </el-form-item>
      <el-form-item label="新闻外链" prop="newsUrl">
        <el-input v-model="ruleForm.newsUrl" clearable />
      </el-form-item>
      <el-form-item label="新闻状态" prop="newsStatus">
        <el-select v-model="ruleForm.newsStatus" clearable>
          <el-option
            v-for="item in validData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="新闻图片" prop="imageUrl">
        <el-upload
          class="avatar-uploader"
          :action="actionUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>

    <!-- 富文本编辑 -->
    <div id="content"></div>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="medium" @click="submitForm('ruleForm')"
        >确定</el-button
      >
      <el-button type="warning" @click="back" size="medium">返回</el-button>
    </div>
  </div>
</template>
<script>
// 引入 wangEditor
import wangEditor from "wangeditor";
export default {
  data() {
    return {
      editor: null,
      imageUrl: "",
      ruleForm: {
        newsType: "",
        newsTitle: "",
        newsStatus: "",
        titleContent: "",
        newsUrl:''
      },
      newsTypeData: [
        {
          label: "网格连心",
          value: 1,
        },
        {
          label: "党员活动",
          value: 2,
        },
      ],
      validData: [
        {
          label: "有效",
          value: 1,
        },
        {
          label: "无效",
          value: 0,
        },
      ],
      rules: {
        newsType: [
          { required: true, message: "请选择新闻类型", trigger: "change" },
        ],
        newsTitle: [
          { required: true, message: "请输入新闻标题", trigger: "blur" },
        ],
        titleContent: [
          { required: true, message: "请输入新闻描述", trigger: "blur" },
        ],
        // imageUrl: [
        //   { required: true, message: "请上传图片", trigger: "blur" },
        // ],
        newsStatus: [
          { required: true, message: "请选择新闻状态", trigger: "change" },
        ],
      },
      disabled: false,
      msg: "",
      isabled: false,
      time: new Date().getTime(),
      flag: true,
    };
  },
  created() {
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.getNewsDetail();
    }
  },
  mounted() {
    this.editor = new wangEditor(`#content`);
    // 配置 onchange 回调函数，将数据同步到 vue 中
    // editor.config.onchange = (newHtml) => {
    //   this.editorData = newHtml;
    // };
    // 相关配置
    // 图片
    this.editor.config.uploadImgShowBase64 = false;
    this.editor.config.showLinkImg = false; //   禁止上传网络图片
    this.editor.config.uploadImgServer = this.actionUrl; // 上传图片的接口地址
 //   this.editor.config.uploadImgHeaders = { Accept: "multipart/form-data" }; // 自定义 header  上传文件格式为file文件，用form-data格式
    this.editor.config.uploadFileName = "file"; // formdata中的name属性
    this.editor.config.uploadImgMaxSize = 5 * 1024 * 1024; // 将图片大小限制为 5M
    this.editor.config.uploadImgMaxLength = 1; // 限制一次最多上传 1张图片
    this.editor.config.uploadImgTimeout = 3 * 60 * 1000; // 设置超时时间

    // 视频
    this.editor.config.uploadVideoServer = this.actionUrl; // 上传图片的接口地址
    this.editor.config.uploadVideoMaxSize = 30 * 1024 * 1024 * 1024; // 1024m
    this.editor.config.withVideoCredentials = true;
    this.editor.config.uploadVideoTimeout = 1000 * 60 * 5; // 5分钟超时
    this.editor.config.uploadVideoName = "file";
    //   this.editor.config.uploadVideoHeaders = { Accept: "multipart/form-data"}; // 自定义 header  上传文件格式为file文件，用form-data格式
    this.editor.config.uploadVideoAccept = ["mp4", "m4v",'wmv'];
    this.editor.config.uploadVideoParams = {
      token: localStorage.getItem("tsToken"), // 设置请求头
    };
    this.editor.config.uploadImgHooks = {
      customInsert: function (insertImg, result, editor) {
        // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
        var url = result.data;
        insertImg(url);

        // result 必须是一个 JSON 格式字符串！！！否则报错
      },
    };
    this.editor.config.uploadVideoHooks = {
      // 视频上传并返回了结果，想要自己把视频插入到编辑器中
      customInsert: function (insertVideoFn, result) {
        // result 即服务端返回的接口
        // insertVideoFn 可把视频插入到编辑器，传入视频 src ，执行函数即可
        insertVideoFn(result.data);
      },
    };

    this.editor.config.customAlert = function (info) {
      //关闭默认提示信息
      // info 是需要提示的内容
      alert("自定义提示：" + info);
    };

    // 创建编辑器
    this.editor.create();
    // this.editor = editor;
  },
  computed: {
    actionUrl() {
      if (process.env.NODE_ENV == "development") {
        return "http://192.168.1.112:10001/api/ueditor/imageUpload";
      } else {
        return `http://web.sanfengcun.com/api/ueditor/imageUpload`;
      }
    },
  },
  methods: {
    // 获取新闻详情
    getNewsDetail() {
      let params = {
        time: this.time,
        id: this.id,
      };
      let result = this.$md5.transferValue(params);
      this.axios
        .post(this.stateUrl.message.detail, {
          time: this.time,
          id: this.id,
          sign: this.$md5.val(result),
        })
        .then((res) => {
          this.editor.txt.html(res.data.data.newsContent);
          this.ruleForm.newsType = res.data.data.type;
          this.ruleForm.newsTitle = res.data.data.title;
          this.ruleForm.newsUrl = res.data.data.newsUrl;
          this.imageUrl = res.data.data.imgPath;
          this.ruleForm.titleContent = res.data.data.titleContent;
          if (res.data.data.status) {
            this.ruleForm.newsStatus = 1;
          } else {
            this.ruleForm.newsStatus = 0;
          }
        })
        .catch(() => {});
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.data;
    },
    beforeAvatarUpload(file) {
      console.log(file);
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error("上传图片大小不能超过 5MB!");
      }
    },
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = "";
          if (this.flag) {
            this.flag = false;
            let params = {
              time: this.time,
              id: this.id ? this.id : "",
              type: this.ruleForm.newsType,
              title: this.ruleForm.newsTitle,
              titleContent: this.ruleForm.titleContent,
              newsUrl:this.ruleForm.newsUrl,
              imgPath: this.imageUrl,
              status: this.ruleForm.newsStatus == 0 ? false : true,
              //   newsContent: this.msg,
            };
            let result = this.$md5.transferValue(params);
            if (!this.id) {
              url = this.stateUrl.message.add;
            } else {
              url = this.stateUrl.message.edit;
            }
            this.axios
              .post(url, {
                time: this.time,
                id: this.id ? this.id : "",
                type: this.ruleForm.newsType,
                title: this.ruleForm.newsTitle,
                titleContent: this.ruleForm.titleContent,
                imgPath: this.imageUrl,
                newsUrl:this.ruleForm.newsUrl,
                status: this.ruleForm.newsStatus == 0 ? false : true,
                newsContent: this.editor.txt.html(),
                sign: this.$md5.val(result),
              })
              .then((res) => {
                if (this.id) {
                  this.msgSuccess("编辑成功");
                } else {
                  this.msgSuccess("添加成功");
                }
                this.$router.back();
                this.flag = true;
              })
              .catch(() => {
                this.flag = true;
              });
          }
        }else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 返回
    back() {
      this.$router.back();
    },
    beforeDestroy() {
      // 调用销毁 API 对当前编辑器实例进行销毁
      this.editor.destroy();
      this.editor = null;
    },
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style lang="less" scoped>
.dialog-footer {
  position: fixed;
  right:20%;
  bottom:30px;
}
/deep/ .el-form {
  width: 60%;
}
#content {
  width: 60%;
  bottom: 50px;
}

</style>

